package com.tuo51.childcare.service.impl;

import com.tuo51.childcare.domain.bize.BizEvaluateDimension;
import com.tuo51.childcare.domain.bize.BizEvaluateQuestion;
import com.tuo51.childcare.domain.bize.BizEvaluateSheet;
import com.tuo51.childcare.domain.carestore.StoreItem;
import com.tuo51.childcare.domain.dailytask.DailyTaskTemplate;
import com.tuo51.childcare.domain.ptest.PTestItem;
import com.tuo51.childcare.domain.vo.BizEvaluateQuestionOptionVO;
import com.tuo51.childcare.domain.vo.DailyTaskTemplateMeta;
import com.tuo51.childcare.domain.vo.PTestItemOptionVO;
import com.tuo51.childcare.repository.*;
import com.tuo51.childcare.service.BizEvaluateImportService;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Dimension;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Question;
import com.tuo51.evaluate.domain.news.ArticleCategory;
import com.tuo51.evaluate.domain.news.ArticleListItem;
import com.tuo51.evaluate.domain.tags.RelObjectTag;
import com.tuo51.evaluate.domain.tags.Tag;
import com.tuo51.evaluate.repositories.article.ArticleCategoryRepository;
import com.tuo51.evaluate.repositories.article.ArticleListItemRepository;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2DimensionRepository;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2QuestionRepository;
import com.tuo51.evaluate.repositories.tags.RelObjectTagRepository;
import com.tuo51.evaluate.repositories.tags.TagRepository;
import com.tuo51.foudation.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tuo51.foudation.constant.APPConstants.TagRelObjectType.*;

@Service
@Slf4j
public class BizEvaluateImportServiceImpl implements BizEvaluateImportService {

    @Autowired
    BizEvaluateSheetRepository sheetRepository;

    @Autowired
    BizEvaluateDimensionRepository dimensionRepository;

    @Autowired
    EvaluateV2DimensionRepository evaluateV2DimensionRepository;

    @Autowired
    BizEvaluateQuestionRepository questionRepository;

    @Autowired
    EvaluateV2QuestionRepository pbQuestionRepository;

    @Autowired
    ArticleListItemRepository itemRepository;

    @Autowired
    StoreItemRepository storeItemRepository;

    @Autowired
    ArticleCategoryRepository categoryRepository;

    @Autowired
    TagRepository tagRepository;

    @Autowired
    RelObjectTagRepository relObjectTagRepository;

    @Autowired
    PTestItemRepository pTestItemRepository;

    @Autowired
    DailyTaskTemplateRepository taskTemplateRepository;

    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Boolean importQuestion(MultipartFile file) {
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //有多少个sheet
            int sheets = workbook.getNumberOfSheets();
            for (int i = 0; i < sheets; i++) {
                XSSFSheet sheet = workbook.getSheetAt(i);

                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();

                //获取标题
                XSSFRow metaRow = sheet.getRow(0);
                String title = metaRow.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                int minMonth = (int) metaRow.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                int maxMonth = (int) metaRow.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                int maxScore = (int) metaRow.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                int minScore = (int) metaRow.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();

                // 获取量表对象
                BizEvaluateSheet evaluateSheet = sheetRepository.getBySheetNameAndDeletedIsFalse(title);
                if (evaluateSheet == null){
                    evaluateSheet = new BizEvaluateSheet();
                    evaluateSheet.setSheetName(title.trim());
                    evaluateSheet.setMaxScore(maxScore);
                    evaluateSheet.setMinScore(minScore);
                    evaluateSheet.setMonth_min(minMonth);
                    evaluateSheet.setMonth_max(maxMonth);
                    sheetRepository.save(evaluateSheet);
                }else{
                    //删除量表下所有数据
                    dimensionRepository.deleteAllBySheetId(evaluateSheet.getId());

                    questionRepository.deleteAllBySheetId(evaluateSheet.getId());
                }


                //遍历每一行，注意：第 0 行为标题, 第1行为表头
                for (int j = 2; j < rows; j++) {
                    //获得第 j 行
                    XSSFRow row = sheet.getRow(j);

                    //序号	题目	准备用具	测评维度	适用月龄
                    String passingCriteria = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String operationGuide = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    double factor = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                    String scores = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String options = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String dimensionName = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String questionTitle = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    int paperIndex = (int)row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();

                    if (StringUtils.isAnyBlank(options, dimensionName, questionTitle, scores)){
                        continue;
                    }

                    BizEvaluateDimension dimension = dimensionRepository.getBySheetIdAndName(evaluateSheet.getId(), dimensionName.trim());
                    if(dimension == null){
                        dimension = new BizEvaluateDimension();
                        dimension.setCode(paperIndex);
                        dimension.setName(dimensionName);
                        dimension.setSheetId(evaluateSheet.getId());
                        dimensionRepository.save(dimension);
                    }

                    //
                    BizEvaluateQuestion question = new BizEvaluateQuestion();
                    question.setTitle(questionTitle);
                    question.setIndexOnPaper(paperIndex);
                    question.setFactor(factor);
                    question.setSheetId(evaluateSheet.getId());
                    question.setDimensionId(dimension.getId());

                    //处理选项
                    String[] choices = options.split("\\|");
                    String[] choiceScores = scores.split("\\|");

                    List<BizEvaluateQuestionOptionVO> answers = new ArrayList();
                    if (choices.length != 0 && choices.length == choiceScores.length){
                        for (int x = 0; x < choices.length; x++){
                            String choice = choices[x];
                            String choiceScore = choiceScores[x];

                            BizEvaluateQuestionOptionVO option = new BizEvaluateQuestionOptionVO(choice, Integer.parseInt(choiceScore), x, false);
                            answers.add(option);
                        }
                    }
                    question.setOptions(answers);


                    questionRepository.save(question);

                }
            }

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean importArticles(String channel, MultipartFile file) {

        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //有多少个sheet
            int sheets = workbook.getNumberOfSheets();
            for (int i = 0; i < sheets; i++) {
                XSSFSheet sheet = workbook.getSheetAt(i);

                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();

                //遍历每一行，注意：第 0 行为标题, 第1行为表头
                for (int j = 1; j < rows; j++) {
                    //获得第 j 行
                    XSSFRow row = sheet.getRow(j);

                    //文章标题	文章链接	信息分类
                    String title = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String url = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String categories = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                    if (StringUtils.isAnyBlank(title, url, categories)){
                        continue;
                    }

                    ArticleListItem listItem = createArticleIfNotExist(channel,title,url,categories);

                    //分类对象创建
                    createArticleCategory(channel, categories, false);
                }
            }

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean importVideos(String channel, MultipartFile file) {

        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //有多少个sheet
            int sheets = workbook.getNumberOfSheets();
            for (int i = 0; i < sheets; i++) {
                XSSFSheet sheet = workbook.getSheetAt(i);

                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();

                //遍历每一行，注意：第 0 行为标题, 第1行为表头
                for (int j = 1; j < rows; j++) {
                    //获得第 j 行
                    XSSFRow row = sheet.getRow(j);

                    //文章标题	文章链接	信息分类
                    int col = 0;
                    String category = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String extFlag = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                    String filename = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    int index = (int)row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                    String title = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    int monthMin = (int)row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                    int monthMax = (int)row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();

                    String dimensionTags = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    String contentTags = row.getCell(col++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                    if (StringUtils.isAnyBlank(category, filename, title, dimensionTags, contentTags)){
                        continue;
                    }

                    String tagStr = dimensionTags + "|" + contentTags;

                    String url = "https://e.res.tuo51.com/carestore/Act-ss-mp4-sd/" + category + "_" + filename;

                    log.info(String.format("processing \n%s\n%s\n%s\n%s\n%s", channel, title, url, category, tagStr));


                    //分类对象创建
                    category =  "育儿宝典-" + category;
                    createArticleCategory(channel, category, true);

                    //创建文章
                    ArticleListItem listItem = createArticleIfNotExist(channel, title, extFlag, url, category, tagStr);

                }
            }

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }
    private void createArticleCategory(String channel, String category, boolean hidden){

        String[] comps = category.split("-+");
        if (comps.length == 0){
            return;
        }

        ArticleCategory parent = null;
        for (String comp : comps){
            String[] subComps = comp.split("、");

            for (String subComp : subComps) {
                ArticleCategory c = null;
                if(parent != null) {
                    String parentId = parent.getId();
                    c = categoryRepository.findByTitleAndChannelAndParentIdAndDeletedIsFalse(subComp, channel, parentId);
                }else{
                    c = categoryRepository.findByTitleAndChannelAndParentIdIsNullAndDeletedIsFalse(subComp, channel);
                }
                if (null == c) {
                    c = new ArticleCategory();
                    c.setChannel(channel);
                    c.setTitle(subComp);
                    c.setParentId(parent != null ? parent.getId() : null);
                    c.setHidden(hidden);
                    categoryRepository.saveAndFlush(c);
                }

                if (subComps.length == 1 && parent == null){
                    parent = c;
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean importPrivateArticles(String channel, MultipartFile file){
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //有多少个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();

            //遍历每一行，注意：第 0 行为表头
            for (int j = 1; j < rows; j++) {
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);

                //文章标题	"儿心量表标签
                //月龄段"	"儿心量表标签
                //对应能力"	文章链接
                //创建文章
                String title = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String month = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String categories = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String url = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                if (StringUtils.isAnyBlank(title, month, url, categories)){
                    continue;
                }

                log.info(String.format("processing \n%s\n%s\n%s\n%s", title, month, categories, url));

                // 创建文章
                ArticleListItem listItem = createArticleIfNotExist(channel,title,url,categories);

                // 创建对应tag
                Tag tag = tagRepository.findByTitleAndHidden(listItem.getId(), true);
                if (tag == null) {
                    tag = new Tag();
                    tag.setTitle(listItem.getId());
                    tag.setHidden(true);
                    tagRepository.save(tag);
                }

                // 创建文章tag关系
                RelObjectTag rel = relObjectTagRepository.findByTagIdAndObjIdAndObjType(tag.getId(), listItem.getId(), NEWSITEM.getValue());
                if (rel == null){
                    rel = new RelObjectTag();
                    rel.setObjType(NEWSITEM.getValue());
                    rel.setObjId(listItem.getId());
                    rel.setTagId(tag.getId());
                    relObjectTagRepository.save(rel);
                }

                //创建所有的问题tag
                int indexBase = 4;
                int paperIndex = (int)row.getCell(indexBase, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                while (paperIndex > 0){
                    //创建index关系
                    EvaluateV2Question q = pbQuestionRepository.getByIndexOnPaperAndDeletedIsFalse(paperIndex);
                    if (q != null){
                        //创建问题，tag关系
                        RelObjectTag r = relObjectTagRepository.findByTagIdAndObjIdAndObjType(tag.getId(), q.getId(), QUESTION.getValue());
                        if(r == null) {
                            r = new RelObjectTag();
                            r.setObjType(1);
                            r.setObjId(q.getId());
                            r.setTagId(tag.getId());
                            relObjectTagRepository.save(r);
                        }
                    }

                    indexBase += 1;
                    paperIndex = (int)row.getCell(indexBase, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                }
            }

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }

    private ArticleListItem createArticleIfNotExist(String channel, String title, String extFlag, String url, String categories, String tags){
        ArticleListItem listItem = null;

        if (StringUtils.isEmpty(channel)){
            listItem = itemRepository.findFirstByTitleAndChannelIsNullAndDeletedIsFalse(title);
        }else{
            listItem = itemRepository.findFirstByTitleAndChannelAndDeletedIsFalse(title, channel);
        }

        if (listItem != null){
            return listItem;
        }

        listItem = new ArticleListItem();
        listItem.setExtFlag(extFlag);
        listItem.setTitle(title);
        listItem.setTags(tags);
        listItem.setChannel(channel);
        listItem.setLinkURL(url);
        listItem.setCategories(categories);

        ArticleCategory ac = categoryRepository.findTop1ByTitleAndChannelAndDeletedIsFalse(categories, channel);
        if (ac != null){
            listItem.setCategoryId(ac.getId());
        }

        itemRepository.save(listItem);

        return listItem;
    }


    private ArticleListItem createArticleIfNotExist(String channel, String title, String url, String categories){

        String tags = "";

        String[] tagNtitle = title.split("\\||】");
        if (tagNtitle.length > 1){
            title = tagNtitle[1];
            tags = tagNtitle[0].replaceAll("【","");
        }

        //处理分类
        if (StringUtils.isNotEmpty(categories)){
            String[] comps = categories.split("-+|、");
            if (comps.length > 0) {
                categories = String.join("|", comps);
            }
        }

        return createArticleIfNotExist(channel, title, null, url, categories, tags);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean importStoreItemsTagsQuestions(String channel, MultipartFile file){
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            //有多少个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            //获取多少行
            int rows = sheet.getPhysicalNumberOfRows();

            //遍历每一行，注意：第 0 行为表头
            for (int j = 1; j < rows; j++) {
                //获得第 j 行
                XSSFRow row = sheet.getRow(j);

                // 歌名
                // 文件名
                // 标签
                // 儿心量表序号
                double index = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                String title = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String filename = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                String categories = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                double month = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                double monthMax = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();

                if (StringUtils.isAnyBlank(title, categories)){
                    continue;
                }

                log.info(String.format("processing \n%s\n%s\n%s", title, filename, categories));

                // 创建文章
                StoreItem storeItem = createStoreItemIfNotExist(channel, title, filename, categories, (int)month, (int)monthMax);

                // 创建对应tag
                Tag tag = tagRepository.findByTitleAndHidden(storeItem.getId(), true);
                if (tag == null) {
                    tag = Tag.of(title, true, null);

                    tagRepository.save(tag);
                }

                // 创建文章tag关系
                RelObjectTag rel = relObjectTagRepository.findByTagIdAndObjIdAndObjType(tag.getId(), storeItem.getId(), STOREITEM.getValue());
                if (rel == null){
                    rel = RelObjectTag.of(tag.getId(), storeItem.getId(), STOREITEM.getValue());

                    relObjectTagRepository.save(rel);
                }

                //创建所有的问题tag
                int indexBase = 6;
                int paperIndex = (int)row.getCell(indexBase, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                while (paperIndex > 0){
                    //创建index关系
                    EvaluateV2Question q = pbQuestionRepository.getByIndexOnPaperAndDeletedIsFalse(paperIndex);
                    if (q != null){
                        //创建问题，tag关系
                        RelObjectTag r = relObjectTagRepository.findByTagIdAndObjIdAndObjType(tag.getId(), q.getId(), QUESTION.getValue());
                        if(r == null) {
                            r = RelObjectTag.of(tag.getId(), q.getId(), QUESTION.getValue());

                            relObjectTagRepository.save(r);
                        }
                    }

                    indexBase += 1;
                    paperIndex = (int)row.getCell(indexBase, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getNumericCellValue();
                }
            }

        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }


    private StoreItem createStoreItemIfNotExist(String channel, String title, String filename, String categories, Integer month, Integer monthMax){
        StoreItem storeItem;

        if (StringUtils.isEmpty(channel)){
            storeItem = storeItemRepository.findFirstByTitleAndChannelIsNullAndDeletedIsFalse(title);
        }else{
            storeItem = storeItemRepository.findFirstByTitleAndChannelAndDeletedIsFalse(title, channel);
        }

        if (storeItem != null){
            return storeItem;
        }

        storeItem = new StoreItem();

        String[] tagNtitle = title.split("\\||】");

        if (tagNtitle.length > 1){
            storeItem.setTags(tagNtitle[0].replaceAll("【",""));
            storeItem.setTitle(tagNtitle[1]);
        }else{
            storeItem.setTitle(title);
        }

        if (StringUtils.isNotEmpty(filename)) {
            storeItem.setMedia("https://e.res.tuo51.com/carestore/Act-ss-mp4-sd/" + filename);
        }
        storeItem.setChannel(channel);
        storeItem.setMonth(month);
        storeItem.setMonthMax(monthMax);

        //处理分类
        if (StringUtils.isNotEmpty(categories)){
            String[] comps = categories.split("-+|、");
            if (comps.length > 0) {
                storeItem.setCategories(String.join("|", comps));
            }
        }

        storeItemRepository.save(storeItem);

        return storeItem;
    }

    @Override
    @Transactional
    public Boolean importDemoPtestItems(String channel, MultipartFile file){
        //创建趣味测试测试内容
        List<PTestItem> cache = new ArrayList<>();
        for (int i = 0; i < 6 * 12 * 31; i++){
            for (int j = 0; j < 4; j++){
                PTestItem tips = new PTestItem();
                //标题
                tips.setForDay(i);
                tips.setDailyIndex(j);
                tips.setTitle("每日tips:" + j + ":" + i);
                tips.setRef("https://www.baidu.com");
                tips.setImages("https://e.res.tuo51.com/public/static/news/home_assess_1.jpg");

                //类型
                tips.setItemType(PTestItem.ITEMTYPE_TIPS);

                cache.add(tips);

                PTestItem ptest = new PTestItem();
                //标题
                ptest.setForDay(i);
                ptest.setDailyIndex(j);
                ptest.setTitle("每日问题:问题问题问题问题问题问题问题问题问题" + j + ":" + i);
                ptest.setHint("每日问题：提示内容提示内容提示内容提示内容提示内容提示内容");
                ptest.setRef("https://www.baidu.com");
                ptest.setImages("https://e.res.tuo51.com/public/static/news/home_assess_1.jpg");

                //类型
                ptest.setItemType(PTestItem.ITEMTYPE_QUESTION);

                //答案
                ptest.setAnswerType(PTestItem.ANSWERTYPE_TOF);

                ptest.setMultipleCount(1);

                List<PTestItemOptionVO> options = Arrays.asList(
                        PTestItemOptionVO.of("https://e.res.tuo51.com/public/static/news/home_assess_2.jpg", "答案", true),
                        PTestItemOptionVO.of("https://e.res.tuo51.com/public/static/news/home_assess_3.jpg", "非答案", false)
                );
                ptest.setOptions(options);

                cache.add(ptest);
            }
        }

        pTestItemRepository.saveAll(cache);

        return true;
    }

    @Override
    public Boolean importDailyTasks(String channel, MultipartFile file){
        if (file==null) {
            throw  new BusinessException("12345", "file 不能为空");
        }

        try {

            List<EvaluateV2Dimension> dimensions = evaluateV2DimensionRepository.findAllByDeletedOrderByCode(false);
            Map<String, EvaluateV2Dimension> dimensionCache = dimensions.stream().collect(Collectors.toMap(EvaluateV2Dimension::getName, o -> o));

            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            int sheetCount = workbook.getNumberOfSheets();
            for (int i = 0; i < sheetCount; i++) {
                XSSFSheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();

                Integer month = Integer.parseInt(sheetName.replaceAll("月龄",""));

                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();

                int r = 2; // 第一行第二行 标题,
                for (; r < rows; r ++){

                    XSSFRow row = sheet.getRow(r);
                    String dimensionName = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                    EvaluateV2Dimension dimension = dimensionCache.get(dimensionName);
                    int c = 1;
                    while (c < row.getLastCellNum()){
                        String name = row.getCell(c++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                        String content = row.getCell(c++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                        String times = row.getCell(c++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();
                        String duration = row.getCell(c++, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();

                        //开始处理数据
                        if (StringUtils.isAnyEmpty(name, content, times, duration)){
                            continue;
                        }

                        //多次/天   1-2次/天   1次/天  每日1-2次  每日1-2次
                        DailyTaskTemplate template = new DailyTaskTemplate();
                        template.setMonthMin(month);
                        template.setMonthMax(month + 1);
                        template.setTitle(name);
                        template.setDescription(content);
                        template.setDuration(duration);
                        template.setRate(times);

                        if (dimension != null){
                            template.setDimensionId(dimension.getId());
                        }

                        DailyTaskTemplateMeta meta = DailyTaskTemplateMeta.dayPerMonth(1);
                        if (times.contains("2次")){
                            meta.setTimes(2);
                        }else if(times.contains("1")){

                        }else if(times.contains("多次")){
                            meta.setTimes(5);
                        }
                        template.setPlanMeta(meta);

                        taskTemplateRepository.save(template);
//                        System.out.println(JSON.toJSONString(template,true ));
                    }
                }
            }
        } catch (IOException e) {
            throw new BusinessException("12345", "错误");
        }
        return true;
    }

}
